﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;

namespace MyPlanSilverlight.Utils
{
    public class MyHttpClient
    {
          private string postData;
        SynchronizationContext currentContext;

        SendOrPostCallback sopc;

        public void PostData(string url, string data, SynchronizationContext _currentContext, SendOrPostCallback _sopc)
        {
            currentContext = _currentContext;
            Uri endpoint = new Uri(url);
            sopc = _sopc;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(endpoint);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            postData = data;
            request.BeginGetRequestStream(new AsyncCallback(RequestReadySocket), request);
        }

        private void RequestReadySocket(IAsyncResult asyncResult)
        {
            WebRequest request = asyncResult.AsyncState as WebRequest;
            Stream requestStream = request.EndGetRequestStream(asyncResult);

            using (StreamWriter writer = new StreamWriter(requestStream))
            {
                writer.Write(postData);
                writer.Flush();
            }

            request.BeginGetResponse(new AsyncCallback(ResponseReadySocket), request);
        }

        private void ResponseReadySocket(IAsyncResult asyncResult)
        {
            WebRequest request = asyncResult.AsyncState as WebRequest;
            WebResponse response = request.EndGetResponse(asyncResult);
            using (Stream responseStream = response.GetResponseStream())
            {
                StreamReader reader = new StreamReader(responseStream);
                string paramStr = reader.ReadToEnd();
                currentContext.Post(sopc, paramStr);
            }
        }
    }
}
